/**
 * 提取创建机构和更新机构中的公共逻辑
 * 1. 机构选择
 * 2. 营业执照上传
 */
import { Component, Vue } from 'vue-property-decorator'
import service from '@/lib/service'
import { Action, State } from 'vuex-class'
import { ElForm } from 'element-ui/types/form'
import { RootState } from '@/store'

@Component
export default class CreateUpdateMixin extends Vue {
  @State((state: RootState) => state.user.accountMobile)
  accountMobile!: string
  @State((state: RootState) => state.user.accountName)
  name!: string
  @Action('applyPage/getInitTree') getInitTree!: any
  formData: any = {
    area: [],
    parentOrgCode: '',
    parentOrgName: '',
    licenseFileKey: '',
    licenseFileUrl: '',
  }
  areaData: any[] = []
  loadTree = false
  defaultExpended: any = []
  file: any = {
    status: 'init',
  }
  uploadUrl: string = '/seal/rest/file/uploadPicMulti'
  orgList: Object[] = []

  // 是否已经提交成功
  isDone: boolean = false
  // 设置 5 秒返回列表页面
  timer: number = 5
  // 计时事件
  timerEvt: any = null
  remoteAreaData() {
    return service({
      url: '/seal/rest/organize/getArea',
      method: 'POST',
    }).then(res => {
      this.areaData = res.data
    })
  }

  areaChange() {
    this.selectOrg({})
  }

  selectOrg(val: any) {
    this.formData.parentOrgName = ''

    this.$nextTick(() => {
      this.formData.parentOrgName = val.fullName || ''
      this.formData.parentOrgCode = val.uuid || ''
    })
  }

  getAllTree(data: {
    uuid: string
    resolve: any
    text: string
    isFirst: boolean
  }) {
    // 初始化树
    if (!this.formData.area) {
      this.$message.warning('请选择区域')

      return
    }

    this.defaultExpended = []
    this.loadTree = data.isFirst

    return this.getInitTree({
      uuid: data.uuid || this.formData.area.slice(-1)[0],
      fullName: (data.text || '').trim(),
    })
      .then((res: any) => {
        this.orgList = res
        this.loadTree = false
        const result = res.map((item: any) => {
          return {
            ...item,
            selectable: true,
            isLeaf: !!(data.text || '').trim() ? true : item.subFlag === 0,
          }
        })
        this.setStatus(result, !!(data.text || '').trim())
        data.resolve(result)
      })
      .catch(() => {
        this.loadTree = false
      })
  }

  selectTreeError(obj: any) {
    // 当提示没有选择区域时
    if (obj.code === 4001) {
      // 自动弹起区域选择
      const { areaSelect } = this.$refs as any
      areaSelect.$el.querySelector('input').click()
    }
  }

  setStatus(data: any[], ignore: boolean) {
    data.forEach((item: any) => {
      item.isLeaf = ignore ? true : !item.subFlag
      if (item.subList) {
        this.defaultExpended.push(item.uuid)
        this.setStatus(item.subList, ignore)
      }
    })
  }

  uploadSuccess(response: any) {
    if (response.errCode === 0) {
      this.formData.licenseFileUrl = response.data.fileUrl
      this.formData.licenseFileKey = response.data.fileKey
    }
  }

  uploadError() {
    this.$message.error('文件上传失败')
  }

  beforeUpload(file: any) {
    const isJPG = /(png|jpe*?g)/i.test(file.type)
    const isLimit = file.size / 1024 / 1024 < 10
    if (!isJPG) {
      this.$message.error('格式须为 PNG/JPG/JPEG')

      return false
    }
    if (!isLimit) {
      this.$message.error(`申请表大小不能超过 10MB。`)

      return false
    }
  }

  deleteImageEvt() {
    this.formData.licenseFileKey = ''
    this.formData.licenseFileUrl = ''
  }

  submitEvt() {
    const form = this.$refs.form as ElForm

    // 用于处理上级机构回显功能
    const temOrgName = this.formData.parentOrgName
    this.formData.parentOrgName = ''
    // 先清空内容再回显以前的选择内容
    this.$nextTick(() => {
      this.formData.parentOrgName = temOrgName
    })

    if (!this.formData.licenseFileKey) {
      this.$message.warning('请选择你要提交的图片')

      return
    }

    form.validate(result => {
      if (result) {
        service({
          url: '/seal/rest/organize/applyNewOrganization',
          method: 'POST',
          body: this.formData,
        }).then(res => {
          if (res.data.success) {
            this.gotoListPage()
          }
        })
      }
    })
  }

  gotoListPage(immediately?: boolean) {
    this.isDone = true
    clearInterval(this.timerEvt)

    if (immediately) {
      this.$router.push('/home/organizationManagement')

      return
    }

    this.timerEvt = setInterval(() => {
      if (!this.timer) {
        this.$router.push('/home/organizationManagement')
        clearInterval(this.timerEvt)

        return
      }

      this.timer--
    }, 1e3)
  }
}
